/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DVDUI.java
 *
 * Created on 2010.11.10., 1:23:51
 */

package workshopdesign.UI;

import java.text.SimpleDateFormat;
import java.util.Collection;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import org.jdesktop.application.Action;
import workshopdesign.Control.DVDController;
import workshopdesign.Control.LoanController;
import workshopdesign.Model.DVD;

/**
 *
 * @author Dom
 */
public class DVDUI extends javax.swing.JPanel implements BaseUIController{

    private DVDController dvd_controller = DVDController.getDVDControl();

    private SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getInstance();

    private DVDDetailUI dVDDetailUI;
    private CopyDetailUI copyDetailUI;
    private LoanListUI loanListUI;
    private PersonDetailUI personDetailUI;
    private DefaultTableModel model;
    private TableRowSorter<DefaultTableModel> sorter;

    /** Creates new form DVDUI */
    public DVDUI() {
        initComponents();

        dVDDetailUI = new DVDDetailUI(this, "Details", true);
        copyDetailUI = new CopyDetailUI(this, "Add copy", true);
        loanListUI = new LoanListUI(this, "Loans");
        personDetailUI = new PersonDetailUI(this, "Rented by", false);

        copyDetailUI.setDvd(null);
        // TODO: DVD list UI goes here
        detail_splitter.setTopComponent(dVDDetailUI);
        detail_splitter.setBottomComponent(copyDetailUI);
        dvd_loan_splitter.setTopComponent(loanListUI);
        dvd_loan_splitter.setBottomComponent(personDetailUI);

        model = (DefaultTableModel) dvd_table.getModel();
        sorter = new TableRowSorter<DefaultTableModel>(model);
        dvd_table.setRowSorter(sorter);

        filter_field.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                filter_data();
            }
        });

        DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
        TableColumn id_column = new TableColumn(0, 25);
        id_column.setHeaderValue("Id");
        columnModel.addColumn(id_column);

        TableColumn title_column = new TableColumn(1, 75);
        title_column.setHeaderValue("Title");
        columnModel.addColumn(title_column);

        TableColumn director_column = new TableColumn(2, 75);
        director_column.setHeaderValue("Director");
        columnModel.addColumn(director_column);

        TableColumn date_column = new TableColumn(3, 75);
        date_column.setHeaderValue("Publication date");
        columnModel.addColumn(date_column);

        dvd_table.setAutoCreateColumnsFromModel(false);
        dvd_table.setColumnModel(columnModel);

        load_dvd_list();
        loanListUI.setDvd(null);
    }

    private void load_dvd_list() {
        sdf.applyPattern("yyyy.MM.dd.");
        
        Collection<DVD> dvd_list = dvd_controller.get_dvd();

        model.setRowCount(dvd_list.size());

        int row_id = 0;
        for (DVD dvd : dvd_list) {
            model.setValueAt(dvd.getId(), row_id, 0);
            model.setValueAt(dvd.getTitle(), row_id, 1);
            model.setValueAt(dvd.getDirector(), row_id, 2);
            model.setValueAt(sdf.format(dvd.getPublicationDate()), row_id, 3);

            row_id++;
        }
    }

    private void filter_data(){
        sorter.setRowFilter(RowFilter.regexFilter(".*" + filter_field.getText() + ".*"));
    }

    public void handle_selection(){
        int selected_row = dvd_table.getSelectedRow();

        if (selected_row < 0) {
            dVDDetailUI.clear_dvd();
            return;
        }

        long dvd_id = Long.valueOf(String.valueOf(model.getValueAt(selected_row, 0)));
        DVD dvd = dvd_controller.get_dvd(dvd_id);

        dVDDetailUI.setDvd(dvd);
        copyDetailUI.setDvd(dvd);
        loanListUI.setDvd(dvd);
    }

    @Override
    public void clear_selection() {
        dvd_table.clearSelection();
        personDetailUI.clear_person();
        copyDetailUI.setDvd(null);
    }

    @Override
    public void subselection_changed() {
        personDetailUI.setPerson(loanListUI.get_person_for_selected_loan());
    }

    @Override
    public void update_data() {
        load_dvd_list();
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dvd_context_menu = new javax.swing.JPopupMenu();
        delete_menu_item = new javax.swing.JMenuItem();
        dvd_splitter = new javax.swing.JSplitPane();
        dvd_detail_splitter = new javax.swing.JSplitPane();
        dvd_loan_splitter = new javax.swing.JSplitPane();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        detail_splitter = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        dvd_table = new javax.swing.JTable();
        filter_field = new javax.swing.JTextField();
        filter_label = new javax.swing.JLabel();

        dvd_context_menu.setName("dvd_context_menu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getActionMap(DVDUI.class, this);
        delete_menu_item.setAction(actionMap.get("delete_menu_item")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getResourceMap(DVDUI.class);
        delete_menu_item.setText(resourceMap.getString("delete_menu_item.text")); // NOI18N
        delete_menu_item.setName("delete_menu_item"); // NOI18N
        dvd_context_menu.add(delete_menu_item);

        setName("Form"); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        dvd_splitter.setDividerLocation(550);
        dvd_splitter.setName("dvd_splitter"); // NOI18N

        dvd_detail_splitter.setDividerLocation(300);
        dvd_detail_splitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        dvd_detail_splitter.setMaximumSize(new java.awt.Dimension(300, 2147483647));
        dvd_detail_splitter.setMinimumSize(new java.awt.Dimension(300, 60));
        dvd_detail_splitter.setName("dvd_detail_splitter"); // NOI18N
        dvd_detail_splitter.setPreferredSize(new java.awt.Dimension(300, 259));

        dvd_loan_splitter.setDividerLocation(200);
        dvd_loan_splitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        dvd_loan_splitter.setName("dvd_loan_splitter"); // NOI18N

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel5.border.title"))); // NOI18N
        jPanel5.setName("jPanel5"); // NOI18N

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        jList2.setName("jList2"); // NOI18N
        jScrollPane4.setViewportView(jList2);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                .addContainerGap())
        );

        dvd_loan_splitter.setTopComponent(jPanel5);

        dvd_detail_splitter.setRightComponent(dvd_loan_splitter);

        detail_splitter.setDividerLocation(150);
        detail_splitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        detail_splitter.setName("detail_splitter"); // NOI18N
        dvd_detail_splitter.setLeftComponent(detail_splitter);

        dvd_splitter.setRightComponent(dvd_detail_splitter);

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        dvd_table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Title", "Director", "Publication Date"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        dvd_table.setComponentPopupMenu(dvd_context_menu);
        dvd_table.setName("dvd_table"); // NOI18N
        dvd_table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                dvd_tableMousePressed(evt);
            }
        });
        jScrollPane3.setViewportView(dvd_table);

        filter_field.setText(resourceMap.getString("filter_field.text")); // NOI18N
        filter_field.setName("filter_field"); // NOI18N

        filter_label.setText(resourceMap.getString("filter_label.text")); // NOI18N
        filter_label.setName("filter_label"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(filter_label)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(filter_field, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE))
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filter_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(filter_label))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE))
        );

        dvd_splitter.setLeftComponent(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 809, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, 0)
                    .addComponent(dvd_splitter, javax.swing.GroupLayout.DEFAULT_SIZE, 809, Short.MAX_VALUE)
                    .addGap(0, 0, 0)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 636, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, 0)
                    .addComponent(dvd_splitter, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                    .addGap(0, 0, 0)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void dvd_tableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dvd_tableMousePressed
        handle_selection();
    }

    @Action
    public void borrow_menu_item() {
        int selected_row = dvd_table.getSelectedRow();

        if (selected_row < 0) {
            return;
        }

        // TODO: Complete
    }//GEN-LAST:event_dvd_tableMousePressed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        load_dvd_list();
        dVDDetailUI.load_data();
        loanListUI.load_data();
        personDetailUI.load_data();
    }//GEN-LAST:event_formComponentShown

    @Action
    public void delete_menu_item() {
        int selected_row = dvd_table.getSelectedRow();

        if (selected_row < 0) {
            return;
        }

        long dvd_id = Long.valueOf(String.valueOf(model.getValueAt(selected_row, 0)));

        int answer = JOptionPane.showConfirmDialog(
                this,
                "Do you really want to delete this DVD? ID=" + String.valueOf(dvd_id),
                "Delete DVD",
                JOptionPane.YES_NO_OPTION);

        if (answer != JOptionPane.YES_OPTION) {
            return;
        }

        LoanController.getLoanController().deleteLoansByDVD(dvd_id);

        dvd_controller.remove_dvd(dvd_id);

        load_dvd_list();
        handle_selection();
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem delete_menu_item;
    private javax.swing.JSplitPane detail_splitter;
    private javax.swing.JPopupMenu dvd_context_menu;
    private javax.swing.JSplitPane dvd_detail_splitter;
    private javax.swing.JSplitPane dvd_loan_splitter;
    private javax.swing.JSplitPane dvd_splitter;
    private javax.swing.JTable dvd_table;
    private javax.swing.JTextField filter_field;
    private javax.swing.JLabel filter_label;
    private javax.swing.JList jList2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    // End of variables declaration//GEN-END:variables

}
